package br.com.vpsa.previdordevendas.controller;

import java.util.Calendar;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import br.com.vpsa.previdordevendas.model.pojo.TokenRequest;
import br.com.vpsa.previdordevendas.model.pojo.TokenResponse;
import br.com.vpsa.previdordevendas.model.pojo.UsuarioSessao;
import br.com.vpsa.previdordevendas.model.util.AuthenticationUtil;
import br.com.vpsa.previdordevendas.model.util.HttpUtils;
import br.com.vpsa.previdordevendas.model.util.JsonUtils;
import br.com.vpsa.previdordevendas.model.util.SessionUtil;

@Controller
@RequestMapping("/callback")
public class CallbackController 
{
	public static final String CODE_PARAM = "code";

	public static final String SERVLET_PATH = "/callback";
	
	public static final String ERROR_PARAM = "error";
	
	@RequestMapping(method = RequestMethod.GET)
    public String get( @RequestParam(CODE_PARAM) String code, Map<String, Object> map) 
	{
		try
		{
			TokenRequest token = new TokenRequest(); 
			token.setApp_id(AuthenticationUtil.APP_ID);
			token.setApp_secret(AuthenticationUtil.APP_SECRET);
			token.setRedirect_uri(AuthenticationUtil.REDIRECT_URI);
			token.setGrant_type("authorization_code");
			token.setCode(code);

			String tokenResponseString = HttpUtils.requestPostHttps( AuthenticationUtil.TOKEN_URI, JsonUtils.getJson(token) );
		
			if( tokenResponseString == null || tokenResponseString.isEmpty() ){
				throw new Exception();
			}
			
			TokenResponse tokenResponse = JsonUtils.getObject(tokenResponseString, TokenResponse.class);
			
			if( tokenResponse == null || tokenResponse.getAccess_token() == null || tokenResponse.getAccess_token().isEmpty() ){
				throw new Exception();
			}
			
			UsuarioSessao usuarioSessao = new UsuarioSessao();
			usuarioSessao.setDataLogin(Calendar.getInstance());
			usuarioSessao.setTokenResponse(tokenResponse);
			usuarioSessao.setAtivo(true);
			
			SessionUtil.getSession().setAttribute(UsuarioSessao.USUARIO_SESSION_KEY, usuarioSessao);
			
			return "redirect:analise";
		}
		catch( Exception e )
		{
			return "redirect:"+ AuthenticationUtil.getUrlLoginVpsa() ;
		}
	}
	
}
